<script setup>
import {
    Edit,Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import {ElMessage,ElMessageBox} from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { getallbookcategoryservice ,addbookcategoryservice,getpartuserinfoservice,
    updatauserservice,deleteuserservice,detailbookcategoryservice
} from '@/api/book.js'
//调用后台接口，完成注册
import { userRegisterService, userLoginService } from '@/api/user.js'
import avatar from '@/assets/default.png'
const categorys = ref([])
const usersInfo = ref([])
//定义变量，控制标题
const title = ref('')
const id = ref(0)
const allUserTypes = ref([
    '养护技术人员','专职道路管理人员','普通用户'
])
const cleardata = ()=>{
    findmodel.value.str='';
}
//控制添加分类弹窗
const dialogVisible = ref(false)
const updatedialogVisible = ref(false)
const findmodel = ref({
    str: ''
})
const userlistpart=async()=>{
    let result = await getpartuserinfoservice(findmodel.value.str);
    console.log(result);
    usersInfo.value = result.data;
    console.log(usersInfo.value);
}
userlistpart();

//定义注册和登录的数据模型
const registerData = ref({
    userName: '',
    userType:'',
    passWord: '',
    rePassWord: '',
})


//自定义确认密码的校验函数
const rePasswordValid = (rule, value, callback) => {
    if (value === '') callback(new Error('请再次确认密码'))
    else if (value !== registerData.value.passWord) callback(new Error('请确保两次输入的密码一样'))
    else callback()
}
//用于注册的表单校验模型
const registerDataRules = ref({
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '用户名的长度必须为5~16位', trigger: 'blur' }
    ],
    passWord: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码长度必须为5~16位', trigger: 'blur' }
    ],
    nickName: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        {
            pattern: /^\S{2,10}$/,
            message: '昵称必须是2-10位的非空字符串',
            trigger: 'blur'
        }
    ],
    email: [
        { required: true, message: '请输入用户邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ],
    initPassWord: [
        { required: true, trigger: 'blur' },
    ],
    userType: [
        { required: true, trigger: 'blur' },
    ],
    rePassWord: [
        {required: true, message: '请输入确认密码'},
        { validator: rePasswordValid, trigger: 'blur' }
    ]
})
//展示编辑弹窗
const showDialog = (row)=>{
    title.value='编辑用户信息';
    updatedialogVisible.value=true;
    //数据拷贝   row要和数据库一致
    registerData.value.userName = row.userName;
    registerData.value.userType = row.userType;
    registerData.value.nickName = row.nickName ? row.nickName : '';
    registerData.value.email = row.email ? row.email : '';
    registerData.value.radio = '2';
    //扩展i的属性，将来需要传递给后台，完成分类的修改
    registerData.value.id = row.id;
    id.value = row.id;
    console.log(id.value);
    console.log(registerData.value);
    
}
const add=()=>{
    registerData.value.userName = '';
    registerData.value.passWord = '';
    registerData.value.rePassWord = '';
    dialogVisible.value=true;
    title.value='添加用户'
}
const addUser =async ()=>{
    let result = await userRegisterService(registerData.value);
    if(result.code==0){
        ElMessage.success('添加成功')
        //调用获取所有文章的函数
        userlistpart();
        dialogVisible.value=false;
    }
    else{
        ElMessage.error(result.message ? result.message : '添加失败')
    }
}

const updateUser = async ()=>{
    //调用接口
    console.log(registerData.value);
    let result = await updatauserservice(registerData.value);
    console.log(result);
    if(result.code==0){
        ElMessage.success(result.message ? result.message : '修改成功')
        userlistpart();
        updatedialogVisible.value=false;
    }
    else{
        ElMessage.error(result.message ? result.message : '修改失败')
    }
    
}
//删除分类
const del = (row) => {
    if(row.id==1){
        ElMessage.info("管理员无法删除")
        return;
    }
    ElMessageBox.confirm(
        '你确认删除该用户吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            let result = await deleteuserservice(row.id)
            if(result.code==1){
                ElMessage.error(result.message ? result.message : '删除失败')
            }
            else{
                ElMessage.success('删除成功')
                //再次调用getAllCategory，获取所有文章分类
                userlistpart();
            }
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>系统用户管理</span>
                <div class="extra">
                    <el-button type="primary" @click="add">添加用户</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="查询条件：">
                <el-input v-model="findmodel.str" placeholder="请输入查询内容" width="200"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="userlistpart">搜索</el-button>
                <el-button @click="cleardata">重置</el-button>
            </el-form-item>

        </el-form>
        <el-table :data="usersInfo" style="width: 100%">
            <el-table-column label="序号" width="70" type="index"> </el-table-column>
            <el-table-column label="头像" prop="userPic" width="80">
                <template #default="scope">
                    <el-avatar v-if="scope.row.userPic" :src="scope.row.userPic"></el-avatar>
                    <el-avatar v-else :src="avatar">user</el-avatar>
                </template>
            </el-table-column>
            <el-table-column label="用户名" prop="userName" width="120"></el-table-column>
            <el-table-column label="用户类型" prop="userType" width="150"></el-table-column>
            <el-table-column label="昵称" prop="nickName" width="150"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>
            <el-table-column label="修改时间" prop="updateTime"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
    </el-card>


    <!-- 添加用户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
        <el-form :model="registerData" :rules="registerDataRules" label-width="100px" style="padding-right: 30px">
            <el-form-item label="用户名" prop="userName">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.userName"></el-input>
                </el-form-item>
                <el-form-item label="用户类型" prop="userType">
                    <el-select placeholder="请选择" v-model="registerData.userType">
                    <el-option v-for="c in allUserTypes" :key="c" :label="c" :value="c">
                    </el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="密码" prop="passWord">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.passWord"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="rePassWord">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码"
                        v-model="registerData.rePassWord"></el-input>
                </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addUser"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>
    
    <!-- 修改用户弹窗 -->
    <el-dialog v-model="updatedialogVisible" :title="title"  width="30%">
        <el-form :model="registerData" :rules="registerDataRules" label-width="100px" style="padding-right: 30px">
            <el-form-item label="用户名" prop="userName">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.userName"></el-input>
                </el-form-item>
                <el-form-item label="用户类型" prop="userType">
                    <el-select placeholder="请选择" v-model="registerData.userType">
                    <el-option v-for="c in allUserTypes" :key="c" :label="c" :value="c">
                    </el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input  placeholder="请输入昵称"
                        v-model="registerData.nickName"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input  placeholder="请输入邮箱"
                        v-model="registerData.email"></el-input>
                </el-form-item>
                <el-form-item label="初始化密码" prop="initPassWord">
                    <el-radio v-model="registerData.radio" label="1" click="registerData.value.radio='1'">是</el-radio>
                    <el-radio v-model="registerData.radio" label="2">否</el-radio>
                </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="updatedialogVisible = false">取消</el-button>
                <el-button type="primary" @click="updateUser"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>
</template>


<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;
    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>